package com.shuyu.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuyu.common.utils.SecurityUtils;
import com.shuyu.common.utils.StringUtils;
import com.shuyu.domain.*;
import com.shuyu.mapper.ApprovalProcessDetailMapper;
import com.shuyu.service.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ApprovalProcessDetailServiceImpl extends ServiceImpl<ApprovalProcessDetailMapper,ApprovalProcessDetail> implements ApprovalProcessDetailService {
    @Resource
    private ApprovalProcessService approvalProcessService;
    @Resource
    private ApprovalProcessNodeService approvalProcessNodeService;
    @Resource
    private ApprovalProcessFlowService approvalProcessFlowService;
    @Resource
    private ProductService productService;
    @Resource
    private ActivityService activityService;
    @Resource
    private ApprovalAuthorizeService approvalAuthorizeService;

    @Override
    public void createApprovalProcess(int type, int operationType, Integer sourceId) {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        ApprovalProcess approvalProcess = approvalProcessService.getOne(new LambdaUpdateWrapper<ApprovalProcess>().eq(ApprovalProcess::getType, type).last("limit 1"));
        if(approvalProcess == null){
            if(type==1){
                Product product = new Product();
                product.setAuditStatus(1);
                product.setId(sourceId);
                productService.updateById(product);
            }else if(type==3){
                Activity activity = new Activity();
                activity.setAuditStatus(1);
                activity.setId(sourceId);
                activityService.updateById(activity);
            }
            return;
        }
        int processId = approvalProcess.getId();
        List<ApprovalProcessNode> approvalProcessNodeList = approvalProcessNodeService.list(new LambdaQueryWrapper<ApprovalProcessNode>().eq(ApprovalProcessNode::getProcessId, processId).orderByAsc(ApprovalProcessNode::getProcessIndex));
        Long auditingUserId = approvalProcessNodeList.get(0).getUserId();
        ApprovalProcessDetail approvalProcessDetail = new ApprovalProcessDetail(processId, type, userId, sourceId, auditingUserId, 0, new Date(), operationType);
        this.save(approvalProcessDetail);
        List<ApprovalProcessFlow> list = new ArrayList<>();
        list.add(new ApprovalProcessFlow(approvalProcessDetail.getId(), userId, 0, 1, new Date()));
        for (ApprovalProcessNode approvalProcessNode : approvalProcessNodeList) {
            list.add(new ApprovalProcessFlow(approvalProcessDetail.getId(), approvalProcessNode.getUserId(), approvalProcessNode.getProcessIndex(), 0, new Date()));
        }
        approvalProcessFlowService.saveBatch(list);
    }

    @Override
    public List<ApprovalProcessDetail> getList(List<Long> userIdProductList, List<Long> userIdActivityList, long userId, String startTime, String endTime, String sourceName, Integer type, String username, Integer auditingStatus) {
        QueryWrapper<ApprovalProcessDetail> query = new QueryWrapper<ApprovalProcessDetail>()
                .eq(ObjectUtil.isNotNull(type),"t1.type", type)
                .le(StringUtils.isNotEmpty(endTime),"t1.create_time", endTime)
                .ge(StringUtils.isNotEmpty(startTime),"t1.create_time", startTime)
                .and(StringUtils.isNotEmpty(sourceName),wrapper->wrapper.like("t2.name",sourceName).or().like("t3.name",sourceName))
                .like(StringUtils.isNotEmpty(username),"t4.nick_name",username)
                .eq(ObjectUtil.isNotNull(auditingStatus),"t1.auditing_status", auditingStatus);
        String sql = "";
        if(CollectionUtil.isNotEmpty(userIdProductList)){
            String ids = StringUtils.join(userIdProductList,",");
            sql += "UNION ALL " +
                    "SELECT DISTINCT t1.* FROM tbl_approval_process_detail t1 left join tbl_approval_process_flow t2 on t1.id=t2.detail_id " +
                    "where t2.user_id in ("+ids+")  and t1.auditing_status=0 and t2.auditing_status=0 and t1.type=1";
        }
        if(CollectionUtil.isNotEmpty(userIdActivityList)){
            String ids = StringUtils.join(userIdActivityList,",");
            sql += "UNION ALL " +
                    "SELECT DISTINCT t1.* FROM tbl_approval_process_detail t1 left join tbl_approval_process_flow t2 on t1.id=t2.detail_id " +
                    "where t2.user_id in ("+ids+")  and t1.auditing_status=0 and t2.auditing_status=0 and t1.type=2";
        }

        return this.baseMapper.getList(query,sql,userId);
    }
}
